package com.aiju.cash.ui.pay;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.aiju.app.IDialogSimpleListener;
import com.aiju.base.activity.BaseTitleActivity;
import com.aiju.cash.R;
import com.aiju.cash.core.api.DataJson;
import com.aiju.cash.core.api.PayApi;
import com.aiju.cash.ui.pay.entity.Pay;
import com.aiju.cash.util.PrivateUtil;
import com.aiju.utils.L;
import com.aiju.utils.T;
import com.aiju.utils.tts.BaiduTTSManager;
import com.aiju.widgit.dialog.MsgDialog;
import com.aiju.widgit.dialog.SimpleDialog;
import com.uuzuche.lib_zxing.activity.CaptureFragment;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import okhttp3.Call;

/**
 * @author: 佐为
 * @date: 2016-12-07 09:25
 * @version: V1.0
 * @Description: 支付宝支付
 */
public class PayZhiFBaoActivity extends BaseTitleActivity {

    private TextView payTimeTextView;

    private boolean isPaySuccess = false;

    private Pay pay;
    private int type;

    private ImageView payTypeImageView;

    private CaptureFragment captureFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_zhifbao);
        setCenterTitle("扫码收款");
        setRightTitle("取消收款");
        pay = (Pay) getIntent().getExtras().getSerializable("pay");
        type = getIntent().getExtras().getInt("type");

        payTypeImageView = (ImageView) findViewById(R.id.iv_pay_type);
        if (type == 0) {
            payTypeImageView.setImageResource(R.mipmap.icon_pay_zhifubao);
        } else if (type == 1) {
            payTypeImageView.setImageResource(R.mipmap.icon_pay_wechat);
        }
        mAiJuTitleBarView.setRightOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new SimpleDialog(PayZhiFBaoActivity.this)
                        .setTitileText("是否取消收款")
                        .setLeftText("否")
                        .setRightText("是")
                        .setOnSimpleClick(new SimpleDialog.OnSimpleClick() {
                            @Override
                            public void onCancel() {
                            }

                            @Override
                            public void onSubmit() {
                                finish();
                            }
                        }).setLayoutParams().show();
            }
        });

        ((TextView) findViewById(R.id.tv_zhif_money)).setText(pay.getPrice());
        captureFragment = new CaptureFragment();
        CodeUtils.setFragmentArgs(captureFragment, R.layout.my_camera);
        captureFragment.setAnalyzeCallback(analyzeCallback);
        getSupportFragmentManager().beginTransaction().replace(R.id.fl_my_container, captureFragment).commit();

        findViewById(R.id.btn_pay_go).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startPayQRCodeActivity(type);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        payTypeImageView.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (captureFragment.isResumed()){
                    PrivateUtil.setFilde(captureFragment, "playBeep", false);
                    PrivateUtil.setFilde(captureFragment, "mediaPlayer", null);
                }
            }
        },100);

    }

    /**
     * 扫描支付
     *
     * @param type
     */
    private void startPayQRCodeActivity(int type) {
        Intent intent1 = new Intent(PayZhiFBaoActivity.this, PayQRCodeActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("pay", pay);
        intent1.putExtras(bundle);
        intent1.putExtra("type", type);
        startActivity(intent1);
        finish();
    }

    @Override
    protected void onDestroy() {
        timer.cancel();
        super.onDestroy();
    }

    /**
     * 倒计时
     */
    private final CountDownTimer timer = new CountDownTimer(1000 * 30, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            payTimeTextView.setText((millisUntilFinished / 1000) + "s");
        }

        @Override
        public void onFinish() {
            L.d("onFinish");
            findViewById(R.id.ly_pay_load).setVisibility(View.INVISIBLE);
            if (!isPaySuccess) {
                new MsgDialog(PayZhiFBaoActivity.this)
                        .setLayoutParams()
                        .setDialogSimpleListener(new IDialogSimpleListener() {
                            @Override
                            public void onCancel(View view) {

                            }

                            @Override
                            public void onConfirm(View view) {
                                finish();
                            }
                        }).show();
            }
        }
    };

    /**
     * 二维码解析回调函数
     */
    CodeUtils.AnalyzeCallback analyzeCallback = new CodeUtils.AnalyzeCallback() {
        @Override
        public void onAnalyzeSuccess(Bitmap mBitmap, String result) {
            findViewById(R.id.ly_pay_load).setVisibility(View.VISIBLE);
            payTimeTextView = (TextView) findViewById(R.id.tv_pay_time);
            timer.start();
            mDialogHelper.showLoadingProgressDialog();
            new PayApi().barCodePay(type, pay.getStoreId(), result, pay.getSubject(), pay.getPrice(),
                    pay.getSumPrice(), mUser.getOperatorId(), mUser.getUserName(), pay.getPrivType(), pay.getPrivPrice(),
                    pay.getShouldPrice(), pay.getActualPrice(), pay.getChangePrice(),
                    pay.getRoundPrice(), pay.getDetail(), new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            T.ToastNetError();
                            timer.cancel();
                            mDialogHelper.dismissProgressDialog();
                            findViewById(R.id.ly_pay_load).setVisibility(View.INVISIBLE);
                        }

                        @Override
                        public void onResponse(String response, int id) {
                            timer.cancel();
                            mDialogHelper.dismissProgressDialog();
                            findViewById(R.id.ly_pay_load).setVisibility(View.INVISIBLE);
                            DataJson json = new DataJson(response);
                            if (json.isPaySuccess()) {

                                L.d("Lifecycle","PayZhiFBaoActivity");
                                Intent intent = new Intent(PayZhiFBaoActivity.this, PaySuccessActivity.class);
                                intent.putExtra("money", pay.getPrice());
                                intent.putExtra("serialNum", json.getOther());
                                startActivity(intent);
                                isPaySuccess = true;

                                String paytype="";
                                if (type == 0){
                                    paytype="支付宝成功收款";
                                }else {
                                    paytype="微信成功收款";
                                }
                                BaiduTTSManager.getInstance().speak(paytype+pay.getPrice()+"元");
                                L.d("支付宝 语音播报");
                            } else {
                                T.ToastShort(json.getMsg());
                            }
                        }
                    });
        }

        @Override
        public void onAnalyzeFailed() {
            T.ToastShort("扫描失败，请重试");
            finish();
        }
    };
}
